<template>
  <ScrollContainer class="pr-4" v-loading="loading" :loading-tip="t('common.loadingText')">
    <div class="pl-2 pr-2">
      <div class="flex justify-center mb-2">
        <a-button type="primary" class="ml-2" @click="handleSave">保存</a-button>
        <a-button type="primary" class="ml-2" @click="handleAdd">增加</a-button>
      </div>
      <template v-if="list && list.length">
        <draggable
          v-model="list"
          :component-data="{
            type: 'transition-group',
          }"
          :animation="180"
          handle=".draggable-item"
        >
          <template #item="{ element, index }">
            <Card
              style="margin-bottom: 5px; width: 100%; overflow: auto"
              :bodyStyle="{ padding: '12px', minWidth: '1250px' }"
            >
              <div class="flex items-center justify-between">
                <div style="width: 50px">规则</div>
                <div>
                  <Input v-model:value="element['desc']" style="width: 150px; margin-right: 5px" />
                </div>
                <div class="w-1/24">如果</div>
                <div class="flex flex-col w-10/24">
                  <div
                    class="w-10/24 flex mb-1 items-center"
                    v-for="(el, elIndex) in element.childLeft"
                    :key="`26${el}`"
                  >
                    <div>
                      <Select
                        :options="formGetFields"
                        class="w-30"
                        v-model:value="el['field']"
                        @change="(val) => getFieldsChange(val, el)"
                      />
                    </div>
                    <div class="ml-1 mr-1">
                      <Select
                        :options="compareOptions"
                        class="w-20"
                        v-model:value="el['operator']"
                      />
                    </div>
                    <div class="flex items-center">
                      <Input
                        v-if="el['val'] == '{$curDate}' || el['val'] == '{$curUser}'"
                        v-model:value="el['curTypeName']"
                        readonly
                        style="width: 150px; margin-right: 5px"
                      />
                      <Select
                        v-else-if="el['mainFormOpt']"
                        :options="formGetFields"
                        v-model:value="el['val']"
                        style="width: 150px; margin-right: 5px"
                      />
                      <template v-else>
                        <FormCtl
                          v-if="el['field'] && el['formCode']"
                          :formCode="el['formCode']"
                          :fieldName="el['field']"
                          v-model:value="el['val']"
                          style="width: 150px; margin-right: 5px"
                        />

                        <Select
                          v-else-if="el['field'] == 'cws_role'"
                          :options="roleList"
                          v-model:value="el['val']"
                          style="width: 150px; margin-right: 5px"
                        />
                        <Input
                          v-else
                          v-model:value="el['val']"
                          style="width: 150px; margin-right: 5px"
                        />
                      </template>
                      <Dropdown>
                        <DownOutlined />
                        <template #overlay>
                          <Menu @click="({ key }) => handleClickMenu(key, el, 'val')">
                            <MenuItem :key="k.value" v-for="k in itemKeys">
                              {{ k.label }}
                            </MenuItem>
                          </Menu>
                        </template>
                      </Dropdown>
                    </div>
                    <div class="cursor-pointer ml-2">
                      <PlusOutlined v-if="elIndex === 0" @click="handleLeftAdd({ element })" />
                      <MinusOutlined v-else @click="handleLeftDelete({ element, elIndex })" />
                    </div>
                  </div>
                </div>
                <div class="w-1/24 p-2">则</div>
                <di class="w-10/24">
                  <div
                    class="flex items-center mb-1"
                    v-for="(el, elIndex) in element.childRight"
                    :key="`363${el}`"
                  >
                    <div class="mr-1" v-if="elIndex != 0">
                      <Select
                        :options="logicalOptions"
                        class="w-80px"
                        v-model:value="el['logical']"
                      />
                    </div>
                    <div>
                      <Select
                        :options="formGetFields"
                        class="w-150px"
                        v-model:value="el['field']"
                        @change="(val) => getFieldsChange(val, el)"
                      />
                    </div>
                    <div class="ml-1 mr-1">
                      <Select
                        :options="compareOptions"
                        class="w-20"
                        v-model:value="el['operator']"
                      />
                    </div>
                    <div class="flex items-center">
                      <Input
                        v-if="el['val'] == '{$curDate}' || el['val'] == '{$curUser}'"
                        v-model:value="el['curTypeName']"
                        readonly
                        style="width: 150px; margin-right: 5px"
                      />
                      <Select
                        v-else-if="el['mainFormOpt']"
                        :options="formGetFields"
                        v-model:value="el['val']"
                        style="width: 150px; margin-right: 5px"
                      />
                      <template v-else>
                        <FormCtl
                          v-if="el['field'] && el['formCode']"
                          :formCode="el['formCode']"
                          :fieldName="el['field']"
                          v-model:value="el['val']"
                          style="width: 150px; margin-right: 5px"
                        />

                        <Select
                          v-else-if="el['field'] == 'cws_role'"
                          :options="roleList"
                          v-model:value="el['val']"
                          style="width: 150px; margin-right: 5px"
                        />
                        <Input
                          v-else
                          v-model:value="el['val']"
                          style="width: 150px; margin-right: 5px"
                        />
                      </template>
                      <Dropdown>
                        <DownOutlined />
                        <template #overlay>
                          <Menu @click="({ key }) => handleClickMenu(key, el, 'val')">
                            <MenuItem :key="k.value" v-for="k in itemKeys">
                              {{ k.label }}
                            </MenuItem>
                          </Menu>
                        </template>
                      </Dropdown>
                    </div>
                    <div class="cursor-pointer ml-2">
                      <PlusOutlined v-if="elIndex === 0" @click="handleRightAdd({ element })" />
                      <MinusOutlined v-else @click="handleRightDelete({ element, elIndex })" />
                    </div>
                  </div>
                </di>
                <div class="w-2/24 flex items-center ml-2">
                  <CloseOutlined class="cursor-pointer" @click="handleDelete({ index })" />
                  <drag-outlined class="ml-2 cursor-pointer draggable-item" />
                  <!-- <ArrowUpOutlined
                  class="ml-2 mr-2 cursor-pointer"
                  v-if="index != 0"
                  @click="handleUpOrDown({ index, type: 'up' })"
                />
                <ArrowDownOutlined
                  class="cursor-pointer"
                  v-if="index != list.length - 1"
                  @click="handleUpOrDown({ index, type: 'down' })"
                /> -->
                </div>
              </div>
            </Card>
          </template>
        </draggable>
      </template>
      <div> 注：日期型字段格式，例：2020-10-08，2020-10-09 15:30:10，current表示当前日期 </div>
    </div>
  </ScrollContainer>
</template>
<script lang="ts" setup>
  import { ref, unref, onMounted, computed, watch } from 'vue';
  import { Card, Select, Dropdown, Menu, Input } from 'ant-design-vue';
  import { ScrollContainer } from '/@/components/Container';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { FormCtl } from '/@/components/FormCtl';
  import draggable from 'vuedraggable';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  import { cloneDeep } from 'lodash-es';
  import { getRoleMultilSel } from '/@/api/system/system';
  import {
    PlusOutlined,
    MinusOutlined,
    ArrowUpOutlined,
    ArrowDownOutlined,
    CloseOutlined,
    DownOutlined,
    DragOutlined,
  } from '@ant-design/icons-vue';
  import {
    getFormGetFields,
    getAdminFlowGetViewRule,
    getAdminFlowSetViewRule,
    getFormGetFormElements,
    getAdminFlowCopyViewRule,
    getAdminFlowSyncViewRule,
    getAdminFlowUpdateViewRule,
  } from '/@/api/flowManage/flowManage';
  import {
    down,
    up,
    leftAddRow,
    rightAddRow,
    compareOptions,
    fieldDisplayOptions,
    getviews,
    itemKeys,
    setviews,
    compareOptions2,
    logicalOptions,
  } from './validationRules.data';
  import { getFormGetCheckSetup, getFormUpdateCheckSetup } from '/@/api/formDesign/formDesign';
  // import { getUUID } from '/@/views/formDesigner/utils/common/string';
  import { isArray } from '/@/utils/is';
  const MenuItem = Menu.Item;
  const { createMessage } = useMessage();
  const props = defineProps({
    formCode: {
      type: String as PropType<string>,
      default: '',
    },
  });
  const loading = ref(false);

  const list: any = ref([]);

  //主表删除
  const handleDelete = ({ index }) => {
    list.value.splice(index, 1);
  };
  //主表新增
  const handleAdd = () => {
    const mainAddRow = {
      // id: getUUID(),
      desc: '',
      childLeft: [
        {
          field: '',
          operator: '',
          val: '',
        },
      ],
      childRight: [
        {
          field: '',
          val: '',
          operator: '',
        },
      ],
    };
    list.value.push(cloneDeep(mainAddRow));
  };

  //主表排序
  const handleUpOrDown = ({ index, type }) => {
    let arr = JSON.parse(JSON.stringify(unref(list)));
    list.value = type == 'up' ? up(index, arr) : down(index, arr);
  };

  //子表左侧新增
  const handleLeftAdd = ({ element }) => {
    console.log('element', element);
    element.childLeft.push(cloneDeep(leftAddRow));
  };
  //子表左侧删除
  const handleLeftDelete = ({ element, elIndex }) => {
    element.childLeft.splice(elIndex, 1);
  };

  //子表右侧新增
  const handleRightAdd = ({ element }) => {
    element.childRight.push(cloneDeep(rightAddRow));
  };
  //子表右侧删除
  const handleRightDelete = ({ element, elIndex }) => {
    element.childRight.splice(elIndex, 1);
  };

  //保存
  const handleSave = async () => {
    console.log('handleSave', unref(list));
    const { isValid, inp, views } = setviews(unref(list));
    console.log('setviews', { isValid, inp, views });
    if (!isValid) {
      return createMessage.warning(inp);
    }
    try {
      const params = {
        formCode: props.formCode,
        checkSetup: views,
      };
      loading.value = true;
      // await getAdminFlowUpdateViewRule(params);
      console.log('handleSave params', params);
      getFormUpdateCheckSetup(params).then(() => {
        createMessage.success('操作成功');
      });
    } catch (err) {
      console.log(err);
    } finally {
      loading.value = false;
    }
  };

  //点击菜单
  const handleClickMenu = (key, el, col) => {
    console.log('key', key);
    el[col] = '';
    if (key == 'mainFormOpt') {
      el['mainFormOpt'] = true;
    } else {
      el['mainFormOpt'] = false;
      el[col] = key.toString();

      const obj2 = itemKeys.find((k) => k.value == el[col]);
      if (obj2) {
        el['curTypeName'] = obj2?.label;
      }
    }
    console.log('el', el);
  };

  const formGetFields = ref<Recordable[]>([]);
  const getFormGetFieldsData = async () => {
    let params = {
      formCode: props.formCode,
    };
    if (!params.formCode) return;
    try {
      const data = (await getFormGetFields(params)) || [];
      formGetFields.value = data.map((item) => {
        delete item.options;
        return {
          ...item,
          label: item.title,
          value: item.name,
        };
      });
      // formGetFields.value.unshift({
      //   label: '-角色-',
      //   value: 'cws_role',
      // });
    } catch (err) {
      console.log('getFormGetFieldsData', err);
    }
  };

  //表单change
  const getFieldsChange = (val, el) => {
    el['mainFormOpt'] = false;
    el['val'] = '';
    if (val) {
      const obj = formGetFields.value.find((item) => item.value == val);
      el['fieldType'] = obj?.fieldType;
      el['formCode'] = obj?.formCode;
    } else {
      el['fieldType'] = '';
      el['formCode'] = '';
    }
  };

  //取得表单中的元素，包括控件、表格行、span、div
  const formElementsList = ref<Recordable[]>([]);
  const getFormGetFormElementsData = async () => {
    formElementsList.value = [];
    const data = await getFormGetFormElements({ formCode: props.formCode });
    if (isArray(data)) {
      formElementsList.value = data.map((item) => {
        return {
          ...item,
          label: `${item.tagName}:${item.title}(${item.id})`,
          value: item.id,
        };
      });
    }
  };

  const model = ref({
    views: '',
  });
  const getAdminFlowGetViewRuleData = async () => {
    if (!props.formCode) return;
    try {
      loading.value = true;
      model.value = await getFormGetCheckSetup({ formCode: props.formCode });
      const { data } = getviews({
        views: unref(model).checkSetup,
      });
      list.value = data;
      console.log('list', list.value);
    } finally {
      loading.value = false;
    }
  };

  //获取角色
  const roleList = ref([]);
  async function getDataList() {
    await getRoleMultilSel().then((res) => {
      let data = res || [];
      data.forEach((item) => {
        item.value = item.code;
        item.label = item.description;
      });
      roleList.value = data;
    });
  }
  const fetch = async () => {
    await getFormGetFieldsData();
    await getAdminFlowGetViewRuleData();
    getFormGetFormElementsData();
    getDataList();
  };
  watch(
    () => props.formCode,
    async (newVal) => {
      console.log('DisplayRules-watch', newVal);
      fetch();
    },
    {
      immediate: true,
    },
  );
  onMounted(() => {
    console.log('ValidationRules-onMounted');
  });
</script>
